package com.gang.music.system.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gang.music.system.entity.Menu;
import com.gang.music.system.mapper.MenuMapper;
import com.gang.music.system.service.MenuService;
import com.smallchill.core.toolbox.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gang
 * @since 2017-10-29
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

	@Autowired
	private MenuMapper menuMapper;
	
	@Override
	public List<Menu> findSystemMenu() {
		
		return menuMapper.selectByParentId(0);
	}

	@Override
	public List<Menu> findForTreeTable(int menuId) {
		
		return menuMapper.selectForTreeTable(menuId);
	}

	@Override
	public void deleteById(Integer id) {
		
		List<Menu> childList = menuMapper.selectByParentIdWithChildList(id);
		//要删除的ids
		List<Integer> delMenuIds = new ArrayList<Integer>();
		
		Menu delMenu = new Menu();
		delMenu.setId(id);
		delMenu.setChildMenus(childList);
		//递归获取要删除的ids
		reDelete(delMenu, delMenuIds);
		//batch删除
		menuMapper.batchDelete(delMenuIds);
		
	}

	private void reDelete(Menu menu, List<Integer> delMenuIds) {
		
		if(!Func.isEmpty(menu.getChildMenus()) 
				&& menu.getChildMenus().size() > 0) {
			for (Menu m : menu.getChildMenus()) {
				reDelete(m, delMenuIds);
			}
		}
		delMenuIds.add(menu.getId());
	}

	@Override
	public Menu selectByIdWithParent(Integer id) {
		
		return menuMapper.selectByIdWithParent(id);
	}
}
